package com.zby.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.zby.business.R;
import com.zby.business.activity.Detail;
import com.zby.business.adapter.ShopListViewAdapter;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2016/2/27.
 */
public class MarketFragment extends Fragment implements View.OnClickListener {
    private View view;
    private ImageView showOptionIamge;
    private GridAdapter gridAdapter;
    private LinearLayout categoriesLayout;
    private GridView gridView;
    private Handler handler;
    private ArrayList categories, categoryIndex;
    private boolean isOpen = false;
    private String s = "介绍";
    private ArrayList commodityPrice, commodityName, commoditypicture, commodityIntroduce, commodityDetailId, commoditySale;
    private ListView shopListView;
    private App app;
    private ShopListViewAdapter shopListViewAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.market, null);
        initView();
        getCategory();
        getCommodity(0);
        shopListViewAdapter = new ShopListViewAdapter(getContext(), app.getUserId(), commodityName, commoditypicture, commodityPrice, commodityDetailId);
        shopListView.setAdapter(shopListViewAdapter);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0) {
                    categoriesLayout.setVisibility(View.GONE);
                }
                super.handleMessage(msg);
            }
        };
        return view;
    }

    private void getCategory() {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("getCategory").get();
            System.out.println(s);
            JSONObject object = new JSONObject(s);
            JSONArray category = object.getJSONArray("category");
            for (int i = 0; i < category.length(); i++) {
                JSONObject c = (JSONObject) category.get(i);
                categories.add(c.get("categoryName"));
                categoryIndex.add(c.get("categoryId"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCommodity(int position) {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("searchCategory?categoryId=" + categoryIndex.get(position)).get();
            System.out.println(s);
            JSONObject commodityJsonObject = new JSONObject(s);
            JSONArray commodityArray = commodityJsonObject.getJSONArray("commodity");
            if (commodityArray.length() > 0) {
                clear();
                for (int i = 0; i < commodityArray.length(); i++) {
                    JSONObject commodity = (JSONObject) commodityArray.get(i);
                    commodityDetailId.add(commodity.get("commodityDetailId"));
                    commodityName.add(commodity.get("commodityBrand"));
                    commodityPrice.add(commodity.get("commodityPrice"));
                    commoditypicture.add(commodity.get("commodityPicture"));
                    commodityIntroduce.add(commodity.get("commodityIntroduce"));
                    commoditySale.add(commodity.get("commoditySale"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clear() {
        commodityDetailId.clear();
        commodityIntroduce.clear();
        commoditySale.clear();
        commodityPrice.clear();
        commoditypicture.clear();
        commodityName.clear();
    }

    private void initView() {
        app = (App) getActivity().getApplication();
        commodityName = new ArrayList();
        commoditypicture = new ArrayList();
        commodityPrice = new ArrayList();
        categories = new ArrayList();
        categoryIndex = new ArrayList();
        commodityIntroduce = new ArrayList();
        commodityDetailId = new ArrayList();
        commoditySale = new ArrayList();
        showOptionIamge = (ImageView) view.findViewById(R.id.showOptionImage);
        shopListView = (ListView) view.findViewById(R.id.shopListView);
        showOptionIamge.setOnClickListener(this);
        gridView = (GridView) view.findViewById(R.id.gridView);
        categoriesLayout = (LinearLayout) view.findViewById(R.id.categoriesLayout);
        categoriesLayout.setVisibility(View.GONE);
        gridAdapter = new GridAdapter();
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getCommodity(position);
                shopListViewAdapter.notifyDataSetChanged();
                refresh();

            }
        });
        shopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), Detail.class);
                Bundle bundle = new Bundle();
                bundle.putString("introduce", commodityIntroduce.get(position) + "");
                bundle.putString("price", commodityPrice.get(position) + "");
                bundle.putString("sale", commoditySale.get(position) + "");
                bundle.putString("commodityId", commodityDetailId.get(position) + "");
                bundle.putString("url", commoditypicture.get(position) + "");
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.showOptionImage:
                refresh();
                break;
        }
    }

    private void refresh() {
        Animation animation = null;
        Animation categoryAnimation = null;
        if (isOpen) {
            animation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate45r);
            categoryAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.categories_fadeout);
        } else {
            categoriesLayout.setVisibility(View.VISIBLE);
            animation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate45);
            categoryAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.categories_fadein);
        }
        isOpen = !isOpen;
        showOptionIamge.startAnimation(animation);
        categoriesLayout.startAnimation(categoryAnimation);
        if (!isOpen)
            new DismissThread().start();
    }

    class DismissThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(1500);
                handler.sendEmptyMessage(0);
                System.out.println(0 + "");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            super.run();
        }
    }


    class GridAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return categories.size();
        }

        @Override
        public Object getItem(int position) {
            return categories.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView;
            if (convertView == null) {
                textView = new TextView(getContext());
                textView.setGravity(Gravity.CENTER);
                textView.setText(categories.get(position) + "");
            } else {
                textView = (TextView) convertView;
            }
            return textView;
        }
    }
}
